FogCore.hlsl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef FLAT_KIT_FOG_INCLUDED
  2. #define FLAT_KIT_FOG_INCLUDED
  3. TEXTURE2D_X (_BlitTexture);
  4. SAMPLER (sampler_BlitTexture);
  5. float Linear01Depth(float z)
  6. {
  7. const float isOrtho = unity_OrthoParams.w;
  8. const float isPers = 1.0 - unity_OrthoParams.w;
  9. z *= _ZBufferParams.x;
  10. return (1.0 - isOrtho * z) / (isPers * z + _ZBufferParams.y);
  11. }
  12. float LinearEyeDepth(float z)
  13. {
  14. return rcp(_ZBufferParams.z * z + _ZBufferParams.w);
  15. }
  16. float4 SampleCameraColor(float2 uv)
  17. {
  18. return SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_BlitTexture, UnityStereoTransformScreenSpaceTex(uv));
  19. }
  20. void Fog_float(float2 UV, out float4 Out)
  21. {
  22. float4 original = SampleCameraColor(UV);
  23. float fogBlend = _DistanceHeightBlend;
  24. float depthPacked = SampleSceneDepth(UV);
  25. #if defined(USE_DISTANCE_FOG)
  26. const float depthCameraPlanes = Linear01Depth(depthPacked);
  27. const float depthAbsolute = _ProjectionParams.y + (_ProjectionParams.z - _ProjectionParams.y) * depthCameraPlanes;
  28. const float depthFogPlanes = saturate((depthAbsolute - _Near) / (_Far - _Near));
  29. float4 distanceFog = SAMPLE_TEXTURE2D_X(_DistanceLUT, sampler_DistanceLUT, float2(depthFogPlanes, 0.5));
  30. distanceFog.a *= _DistanceFogIntensity;
  31. #else
  32. float4 distanceFog = float4(0, 0, 0, 0);
  33. fogBlend = 1.0;
  34. #endif
  35. #if defined(USE_HEIGHT_FOG)
  36. #if defined(FOG_CAMERA_RELATIVE)
  37. const float3 worldPos = float3(UV, depthPacked) * LinearEyeDepth(depthPacked) + _WorldSpaceCameraPos;
  38. #else
  39. #if !UNITY_REVERSED_Z
  40. // Adjust z to match NDC for OpenGL
  41. depthPacked = lerp(UNITY_NEAR_CLIP_VALUE, 1, depthPacked);
  42. #endif
  43. const float3 worldPos = ComputeWorldSpacePosition(UV, depthPacked, UNITY_MATRIX_I_VP);
  44. #endif
  45. const float heightUV = saturate((worldPos.y - _LowWorldY) / (_HighWorldY - _LowWorldY));
  46. float4 heightFog = SAMPLE_TEXTURE2D_X(_HeightLUT, sampler_HeightLUT, float2(heightUV, 0.5));
  47. heightFog.a *= _HeightFogIntensity;
  48. #else
  49. float4 heightFog = float4(0, 0, 0, 0);
  50. fogBlend = 0.0;
  51. #endif
  52. const float4 fog = lerp(distanceFog, heightFog, fogBlend);
  53. float4 final = lerp(original, fog, fog.a);
  54. final.a = original.a;
  55. Out = final;
  56. }
  57. #endif // FLAT_KIT_FOG_INCLUDED